const BASE_URL = "http://api-breakingnews-web.itheima.net";

//安全登录验证，防止直接进入首页
//登录了直接访问index
//没登录去首页登录
let token = localStorage.getItem("token");
if (!token) {
  location.href = "/login.html";
}
//获取个人信息
function my_getUserInfo() {
  axios.get(`${BASE_URL}/my/userinfo`, {
      headers: {
        Authorization: token,
      },
    })
    .then((res) => {
      //判断token失效问题
      if (res.data.status === 1 && res.data.message === "身份认证失败！") {
        localStorage.removeItem("token");
        location.href = "/login.html";
        return;
      }

      //解构，单独获取信息
      let { user_pic, nickname, username } = res.data.data;
      //展示昵称
      if (nickname === "") {
        nickname = username;
      }
      $(".nickname").html(nickname);
      // 展示头像
      if (user_pic === null) {
        //   toUpperCase=》转换为大写
        let firstLetter = username[0].toUpperCase();
        // console.log(username.length);//6 cjl123
        $(".avatar").html(firstLetter);
        $(".avatar").css("display", "inline-block");
      } else {
        $(".layui-nav-img").attr("src", user_pic);
        $(".layui-nav-img").css("display", 'inline-block');
      }
    });
}
my_getUserInfo();

//退出返回首页
$("#logout").on("click", function () {
  layer.confirm("确认退出？", { icon: 3, title: "提示" }, function (index) {
    //do something
    localStorage.removeItem("token");
    location.href = "/login.html";

    // 关闭当前弹窗
    layer.close(index);
  });
});
